package com.fortune.cat.resolver;

import com.fortune.cat.bean.RequestRateLimiterConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import static com.fortune.cat.enums.RateLimiterKeyResolverEnums.PATH_QUERY;
import static com.fortune.cat.resolver.PathKeyResolver.antPathMatcher;

/**
 * @author zhaozeyang
 * @date 2019/4/26 14:13
 * @description
 */
@Component
public class PathQueryKeyResolver extends AbstractKeyResolver {
    @Override
    public Integer getType() {
        return PATH_QUERY.getType();
    }

    @Override
    protected String doResolve(ServerWebExchange exchange) {
        RequestRateLimiterConfig.Query query = requestRateLimiterConfig.getQuery();
        String path = exchange.getRequest().getPath().value();
        String method = exchange.getRequest().getMethod().name();
        if (method.equalsIgnoreCase(requestRateLimiterConfig.getMethod()) & antPathMatcher.match(requestRateLimiterConfig.getPath(), path)) {
            if (query.getValue().equals(exchange.getRequest().getQueryParams().getFirst(query.getQuery()))) {
                return method.concat("-").concat(requestRateLimiterConfig.getPath()).concat("-").concat(query.getQuery()).concat("-").concat(query.getValue());
            }
        }
        return null;
    }
}
